using System;
using System.Web.UI;
using System.IO;
using System.Text;
using SoftwareMonkeys.Scriptech.Business;
using SoftwareMonkeys.Scriptech.Diagnostics;

namespace SoftwareMonkeys.Scriptech.Scripts
{

	public class ConsoleWriter : TextWriter
	{
		//public ScriptProcess CurrentProcess;
		public BaseScript CurrentScript;
		public TextWriter InnerWriter;
		
		public ConsoleWriter()
		{
		}
		
		public ConsoleWriter (BaseScript script, TextWriter innerWriter)
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Constructing ConsoleWriter"))
			{
				if (script.CurrentProcess == null)
					LogWriter.Debug("script.CurrentProcess == null");
				
				CurrentScript = script;
				InnerWriter = innerWriter;
			}
		}
		
		public override void Write (string s)
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Writing to console."))
			{
				LogWriter.Debug("Data: " + s);
				
				InnerWriter.Write(s);
				
				if (CurrentScript.CurrentProcess != null)
				{
					CurrentScript.CurrentProcess.AppendOutput(s);
					
					// TODO: Remove false parameter
					//UpdateStrategy.New(CurrentScript.CurrentProcess, false).Update(CurrentScript.CurrentProcess);
				}
			}
		}
		
		public override void WriteLine(string s)
		{	
			using (LogGroup logGroup = LogGroup.StartDebug("Writing to console."))
			{
				LogWriter.Debug("Data: " + s);
				
				InnerWriter.WriteLine(s);
			
				if (CurrentScript.CurrentProcess != null)
				{
					CurrentScript.CurrentProcess.AppendOutput(s);
					
					// TODO: Remove false parameter
					//UpdateStrategy.New(CurrentScript.CurrentProcess, false).Update(CurrentScript.CurrentProcess);
				}
			}
		}
		
		public override void Flush ()
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Flushing console data."))
			{
				if (CurrentScript.CurrentProcess != null)
				{
					UpdateStrategy.New(CurrentScript.CurrentProcess, false).Update(CurrentScript.CurrentProcess);
				}
				base.Flush ();
			}
		}
		
		public override Encoding Encoding {
			get {
				throw new NotImplementedException ();
			}
		}
		
		public void Dispose ()
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Disposing and flushing console writer."))
			{
				Flush();
			}
		}
	}
}

